﻿using System.Collections.Generic;

namespace Game.Plugin.Parse
{
    public class Evaluator : IExpression 
    {
        readonly ICodeObject syntaxTree;

        public Evaluator(string expression)
        {
            var context = new ParserContext();

            foreach (string token in expression.Split(' '))
            {
                var parser = Parsers.Find(token);
                if (parser != null)
                {
                    parser.Parse(token, context);
                }
            }

            if (context.Stack.Count > 0)
            {
                syntaxTree = context.Stack.Pop();
            }
            else
            {
                syntaxTree = new ErrorObject();
            }
        }

        public object Interpret(Dictionary<string, ICodeObject> context) 
        {
            return syntaxTree.Interpret(context);
        }
    }
}
